package com.example.zzl.utils;

import android.databinding.BindingAdapter;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.util.TypedValue;
import android.widget.TextView;

import java.net.URL;

/**
 * Created by ligg on 2017/2/15.
 */

public class Utils {
    @BindingAdapter({"text_one", "text_alias"})
    public static void setText(TextView tv, String tag, String charSequence) {
        Log.e("Utils", "setText: " + charSequence.toString());
        if (tag.equals("") || tag == null) {
            Spanned spanned = Html.fromHtml(charSequence, HtmlImage.newInstance(), null);
            tv.setText(spanned);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        } else {
            tv.setText(tag);
        }

    }

    static class HtmlImage implements Html.ImageGetter {

        private static HtmlImage htmlImage;

        private HtmlImage() {
        }

        ;

        @Override
        public Drawable getDrawable(String source) {
            Drawable drawable=null;
            URL url;
            try {
                url = new URL(source);
                drawable = Drawable.createFromStream(url.openStream(), "");
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            return drawable;
        }

        public static synchronized HtmlImage newInstance() {
            if (htmlImage == null) {
                htmlImage = new HtmlImage();
            }
            return htmlImage;

        }
    }
}
